import * as React from 'react';
import { useEffect, useState } from 'react';
import { Alert, Button, Form, Input, Select, Space, Tooltip, Upload } from 'antd';
import { UploadFile } from 'antd/es/upload/interface';
import { Request } from '@/client';
import { UploadOutlined, QuestionCircleOutlined } from '@ant-design/icons/lib';
import { string2Uint8Array } from '@/utils';
import styles from './style.less';

interface RegistrationInformation {
  macaddress: string;
  appname: string;
  machinecode: string;
  version: string;
}

export interface LicFormProps {
  /**
   * @description 是否多文件上传
   * @default false
   */
  multipleFileUpload?: boolean;

  /**
   * @see https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/file#accept
   */
  acceptFile?: string;

  submit?: (request: Request) => void;
}

const { Item, useForm } = Form;
const { Option } = Select;
const { Dragger } = Upload;
const layout = {
  labelCol: { span: 4 },
  wrapperCol: { span: 19 },
};
const tailLayout = {
  wrapperCol: { offset: 0, span: 24 },
};

const LicForm: React.FC<LicFormProps> = (props) => {
  const { multipleFileUpload, acceptFile, submit } = props;
  const [form] = useForm();
  const [fileList, setFileList] = useState<UploadFile[]>([]);

  useEffect(() => {
    form.submit();
  }, []);

  /**
   * @description 提交请求
   */
  const onFinish = (values: any) => {
    if (fileList.length) {
      submit(values);
    } else {
      delete values.registrationInformation;
      submit(values);
    }
  };

  /**
   * @description 重置表单
   */
  const onRest = () => {
    setFileList([]);
    form.resetFields();
    form.submit();
  };

  return (
    <Form
      {...layout}
      form={form}
      onFinish={onFinish}
      initialValues={{
        options: {
          version: '10.0',
        },
      }}
      className={styles.container}>
      <Item label="访问令牌" name={'accessToken'}>
        <Input
          placeholder={'请输入访问令牌'}
          suffix={
            <Tooltip title={'如何获取访问令牌'}>
              <QuestionCircleOutlined />
            </Tooltip>
          }
        />
      </Item>
      <Item label="动态密码" name={['code']}>
        <Input
          placeholder={'请输入动态验证码'}
          suffix={
            <Tooltip title={'如何获取动态密码'}>
              <QuestionCircleOutlined />
            </Tooltip>
          }
        />
      </Item>
      <Item label="注册信息" name={['registrationInformation']} rules={[{ required: false }]}>
        <div>
          <Alert
            message="通过上传注册信息文件，可自动填充相关字段"
            closable
            type="warning"
            style={{ marginBottom: 24 }}
          />
          <Dragger
            fileList={fileList}
            accept={acceptFile}
            customRequest={(options) => {
              if (multipleFileUpload) {
                setFileList((pre) => [...pre, options.file]);
              } else {
                setFileList([options.file]);
              }
              options.file.text().then((contents) => {
                const info = JSON.parse(contents) as RegistrationInformation;
                form.setFieldsValue({
                  registrationInformation: string2Uint8Array(contents),
                  options: {
                    appName: info.appname,
                    macAddress: info.macaddress,
                    machineCode: info.machinecode,
                    version: info.version,
                  },
                });
              });
            }}
            onRemove={(file) => {
              if (multipleFileUpload) {
                setFileList((pre) => pre.filter((f) => f.uid !== file.uid));
              } else {
                setFileList([]);
              }
            }}>
            <p className="ant-upload-drag-icon">
              <UploadOutlined />
            </p>
            <p className="ant-upload-text">单击或拖动文件到此区域上传</p>
            <p className="ant-upload-hint" />
          </Dragger>
        </div>
      </Item>
      <Item label="版本" name={['options', 'version']} rules={[{ required: false, message: '请选择版本' }]}>
        <Select>
          <Option value="10.0">10.0</Option>
          <Option value="9.0">9.0</Option>
          <Option value="8.0">8.0</Option>
        </Select>
      </Item>
      <Item label="机器码" name={['options', 'machineCode']} rules={[{ required: false, message: '请输入机器码' }]}>
        <Input placeholder={'请输入您的机器码'} />
      </Item>
      <Item
        label="MAC地址"
        name={['options', 'macAddress']}
        rules={[
          { required: false, message: '请输入MAC地址' },
          {
            pattern: '[0-9a-fA-F]{2}(:[0-9a-fA-F]{2}){5}',
            type: 'string',
            message: '请输入正确MAC 例：FA:16:3E:68:DB:65',
          },
        ]}>
        <Input
          placeholder={'请输入 MAC 地址'}
          suffix={
            <Tooltip title={'多个MAC地址用 “,” 进行分割'}>
              <QuestionCircleOutlined />
            </Tooltip>
          }
        />
      </Item>
      <Item label="应用名称" name={['options', 'appName']} rules={[{ required: false, message: '请输入应用名称' }]}>
        <Input placeholder={'请输入应用名称'} />
      </Item>
      <Item {...tailLayout}>
        <Space className={styles.action}>
          <Button type="primary" htmlType="submit" shape="round">
            确认
          </Button>
          <Button type="ghost" htmlType="button" shape="round" onClick={onRest}>
            重置
          </Button>
        </Space>
      </Item>
    </Form>
  );
};

LicForm.defaultProps = {
  acceptFile: '.rif,.txt',
};

export default LicForm;
